package com.heaven.service.impl;

import com.heaven.core.entity.UserEntity;
import com.heaven.customerServer.customerController.vo.user.UserInfoRes;
import com.heaven.exception.BizCodeEnum;
import com.heaven.exception.RRException;
import com.heaven.service.SearchService;
import com.heaven.service.UserService;
import com.heaven.service.VideoService;
import com.heaven.utils.BeanUtils;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

@Service("searchServiceImpl")
public class SearchServiceImpl implements SearchService {
    @Resource
    private VideoService videoService;
    @Resource
    private UserService userService;

    @Override
    public List<UserInfoRes> searchUser(String keyword, String sort, String sessionUserId) {
        // 校验sort
        String[] params = sort.split("-");
        if (params.length != 2 || (!params[1].equals("ASC") && !params[1].equals("DESC"))) {
            throw new RRException(BizCodeEnum.SEARCH_USER_SORT_ARGS_EXCEPTION);
        }

        // 模糊搜索
        Pattern regex = Pattern.compile(keyword);
        Query query = new Query().addCriteria(Criteria.where("status").is(1)
                .orOperator(
                Criteria.where("email").regex(regex),
                Criteria.where("phone").regex(regex),
                Criteria.where("nickname").regex(regex)
                ));

        List<UserEntity> userEntities = userService.selectSort(query, Sort.by(new Sort.Order(Sort.Direction.fromString(params[1]), params[0])));

        // 搜索 sessionUserId 的关注列表
        Set<String> subscribeUsers = userService.selectById(sessionUserId).getSubscribeUsers();

        // 数据清洗
        return userEntities.stream().map(userEntity -> {
            userEntity = userService.initUser(userEntity);
            UserInfoRes res = new UserInfoRes();
            BeanUtils.copyProperties(userEntity, res);

            // 判断是否关注
            if(sessionUserId.isEmpty()) {
                res.setSubscribe(false);
            } else {
                res.setSubscribe(subscribeUsers.contains(res.getUserId()));
            }

            return res;
        }).toList();
    }
}
